<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/7/5
  Time: 18:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图片文件上传</title>
    <script src="js/jquery-3.1.1.js"></script>
</head>
<body>
    <form enctype="multipart/form-data" role="form" action="UploadImgServlet" method="post">
        用户名：<input type="text" name="userName">
        上传图片：<input type="file" name="upload" onchange="showImg(this)" id="uploadFile"><br>
        <div id="localImag">
            <img id="preview" width=-1 height=-1 style="diplay:none" />
        </div>
        <input type="submit" value="上传">
    </form>

        <script>
        function showImg(file) {
            var fileVal = document.getElementById("uploadFile").value;
            var index = fileVal.indexOf(".");
            var lastName = fileVal.substring(index+1,fileVal.length);
            if(lastName=="jpg"||lastName=="png"){
                var preview = document.getElementById('preview');
                if(file.files && file.files[0]){
                    //火狐下
                    preview.style.display = "block";
                    preview.style.width = "300px";
                    preview.style.height = "120px";
                    preview.src = window.URL.createObjectURL(file.files[0]);
                }else{
                    //ie下，使用滤镜
                    file.select();
                    var imgSrc = document.selection.createRange().text;
                    var localImagId = document.getElementById("localImag");
                    //必须设置初始大小
                    localImagId.style.width = "250px";
                    localImagId.style.height = "200px";
                    try{
                        localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                        locem("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
                    }catch(e){
                        alert("您上传的图片格式不正确，请重新选择!");
                        return false;
                    }
                    preview.style.display = 'none';
                    document.selection.empty();
                }
                return true;
            }
        }
    </script>
</body>
</html>
